﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

// Directive for the data model.
using DBDataContext.Model;
using System.Data;
using System;
using System.Data.Linq.SqlClient;

namespace DBViewModel.ViewModel
{
    public class MangaForYouViewModel : INotifyPropertyChanged
    {
        // LINQ to SQL data context for the local database.
        private MangaForYouDataContext MangaForYouDB;

        // Class constructor, create the data context object.
        public MangaForYouViewModel(string toDoDBConnectionString)
        {
            MangaForYouDB = new MangaForYouDataContext(toDoDBConnectionString);
        }

        //
        // TODO: Add collections, list, and methods here.
        //

        // Write changes in the data context to the database.
        public void SaveChangesToDB()
        {
            MangaForYouDB.SubmitChanges();
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify Silverlight that a property has changed.
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        private ObservableCollection<Manga> _allMangas;
        public ObservableCollection<Manga> AllMangas
        {
            get { return _allMangas; }
            set
            {
                _allMangas = value;
                NotifyPropertyChanged("AllMangas");
            }
        }
        // Chapters associated with the manga.
        private ObservableCollection<Chapter> _allChapters;
        public ObservableCollection<Chapter> AllChapters
        {
            get { return _allChapters; }
            set
            {
                _allChapters = value;
                NotifyPropertyChanged("AllChapters");
            }
        }

        // A list of all categories, used by the add task page.
        private List<Chapter> _chaptersList;
        public List<Chapter> ChaptersList
        {
            get { return _chaptersList; }
            set
            {
                _chaptersList = value;
                NotifyPropertyChanged("ChaptersList");
            }
        }

        public void LoadAllMangas(string value)
        {
            try
            {
                if (value != "" || value != string.Empty)
                {
                    // Specify the query to get all chapters
                    var getAllMangas =
                        (from Manga allMangas
                            in MangaForYouDB.Mangas
                         where SqlMethods.Like( value, allMangas.Name) || allMangas.Name.Contains(value) == true                            
                         orderby allMangas.Name
                         select allMangas);

                    // Query the database and get all chapters
                    AllMangas = new ObservableCollection<Manga>(getAllMangas);
                }
                else
                {
                    // Specify the query to get all chapters
                    var getAllMangas =
                        (from Manga allMangas
                            in MangaForYouDB.Mangas
                         orderby allMangas.Name
                         select allMangas);

                    // Query the database and get all chapters
                    AllMangas = new ObservableCollection<Manga>(getAllMangas);
                }
                

            }
            catch
            {

            }
        }

        public void LoadAllChapters()
        {
            try
            {
                // Specify the query to get all chapters
                var getAllChapters =
                    (from Chapter allChapters
                         in MangaForYouDB.Chapters
                     select allChapters);

                // Query the database and get all chapters
                AllChapters = new ObservableCollection<Chapter>(getAllChapters);
            }
            catch
            {

            }

            //ChaptersList = AllChapters.ToList();
        }

        public Manga LoadMangaDefault()
        {
            try
            {
                var query =
                (from Manga manga in MangaForYouDB.Mangas

                 select manga).First();
                return query;
            }
            catch
            {

            }
            return null;
        }

        public void GetChapterListByMangaId(int mangaId)
        {
            try
            {
                // Get list chapter by manga identity
                var getChaptersByMangaId =
                    (from Chapter chapters
                         in MangaForYouDB.Chapters
                     where chapters._mangaId == mangaId
                     //orderby chapters.ChapterName
                     orderby chapters.ChapterId
                     select chapters);

                // Query the database and get all chapters
                AllChapters = new ObservableCollection<Chapter>(getChaptersByMangaId);
            }
            catch
            {

            }

        }

        public Chapter GetChaptersById(int chapterId)
        {
            var query =
                (from Chapter chap in MangaForYouDB.Chapters
                 where chap.ChapterId == chapterId
                 select chap).First();
            return query;
        }

        public Manga GetMangaById(int mangaId)
        {
            var query =
                (from Manga manga in MangaForYouDB.Mangas
                 where manga.MangaId == mangaId
                 select manga).First();
            return query;
        }

        public bool UpdateNeedToDownloadByChapterId(int chapterId)
        {
            try
            {
                // Query to specific chapter
                var chapterUpdate =
                    (from Chapter chap in MangaForYouDB.Chapters
                     where chap.ChapterId == chapterId
                     select chap).First();

                // Change IsDownloaded value by 1 (downloaded)
                chapterUpdate.IsDownloaded = 0;

                // Ask the DataContext to save all the changes.
                MangaForYouDB.SubmitChanges();
                return true; // Update success
            }
            catch
            {
                return false; // Update failed
            }
        }

        public bool UpdateDownloadingById(int chapterId)
        {
            try
            {
                // Query to specific chapter
                var chapterUpdate =
                    (from Chapter chap in MangaForYouDB.Chapters
                     where chap.ChapterId == chapterId
                     select chap).First();

                // Change IsDownloaded value by 1 (downloaded)
                chapterUpdate.IsDownloaded = 2;

                // Ask the DataContext to save all the changes.
                MangaForYouDB.SubmitChanges();
                return true; // Update success
            }
            catch
            {
                return false; // Update failed
            }
        }

        public bool UpdateIsDownloadedByChapterId(int chapterId)
        {
            try
            {
                // Query to specific chapter
                var chapterUpdate =
                    (from Chapter chap in MangaForYouDB.Chapters
                     where chap.ChapterId == chapterId
                     select chap).First();

                // Change IsDownloaded value by 1 (downloaded)
                chapterUpdate.IsDownloaded = 1;

                // Ask the DataContext to save all the changes.
                MangaForYouDB.SubmitChanges();
                return true; // Update success
            }
            catch
            {
                return false; // Update failed
            }

        }


        public Chapter GetChapterByChapterFileName(string tag)
        {
            try
            {
                // Query to specific chapter
                var chapterUpdate =
                    (from Chapter chap in MangaForYouDB.Chapters
                     where chap.ChapterFileName == tag
                     select chap).First();

                return chapterUpdate; // Update success
            }
            catch
            {
                return null; // failed
            }
        }

        // Update IsDownloaded and return chapterID
        public bool UpdateChapterByChapterFileName(string tag)
        {
            try
            {
                // Query to specific chapter
                var chapterUpdate =
                    (from Chapter chap in MangaForYouDB.Chapters
                     where chap.ChapterFileName == tag
                     select chap).First();

                // Change IsDownloaded value by 1 (downloaded)
                chapterUpdate.IsDownloaded = 1;

                // Ask the DataContext to save all the changes.
                MangaForYouDB.SubmitChanges();
                return true; // Update success
            }
            catch
            {
                return false; // Update failed
            }
        }

        // Update current index by chapterId
        public void UpdateCurrentIndexByChapterID(int chapterId, int curIndex)
        {
            try
            {
                // Query to specific chapter
                var chapterUpdate =
                    (from Chapter chap in MangaForYouDB.Chapters
                     where chap.ChapterId == chapterId
                     select chap).First();

                // Change IsDownloaded value by 1 (downloaded)
                chapterUpdate.CurrentIndex = curIndex;

                // Ask the DataContext to save all the changes.
                MangaForYouDB.SubmitChanges();
            }
            catch
            {

            }
        }

        public Chapter GetFirstIsNotDownloadedChapter()
        {
            try
            {
                //  join c in Customers on o.CustomerID equals c.CustomerID
                // Query to specific chapter
                Chapter chapter =
                    (from Chapter chap in MangaForYouDB.Chapters
                     join c in MangaForYouDB.Mangas on chap._mangaId equals c.MangaId
                     where chap.IsDownloaded == 0 && c.IsAutoDownload == true
                     select chap).First();

                return chapter;
            }
            catch
            {
                return null;
            }
        }

        public void InsertNewMangaIntoDatabase(string query, ref int countUpdatedMangas)
        {
            Manga newManga = new Manga();
            string[] parameters = query.Split('@');

            // 0: Name
            // 1: IsCompleted
            // 2: ImageName
            // 3: Description
            // 4: FolderName   
            // 5: IsAutoDownload
            // 6: DataDownloadLink

            newManga.Name = parameters[0];
            newManga.IsCompleted = bool.Parse(parameters[1]);
            newManga.ImageName = parameters[2];
            newManga.Description = parameters[3];
            newManga.FolderName = parameters[4];
            newManga.IsAutoDownload = bool.Parse(parameters[5]);
            newManga.DataLinkDownload = parameters[6];

            List<Manga> testManga =
                (from m in MangaForYouDB.Mangas
                 where m.DataLinkDownload == newManga.DataLinkDownload
                 select m).ToList();

            if (testManga.Count == 0)
            {
                MangaForYouDB.Mangas.InsertOnSubmit(newManga);
                MangaForYouDB.SubmitChanges();

                countUpdatedMangas++;
            }
            // Get MangaID here

        }

        public void InsertChapters(Manga manga, string prefix, int startNum, int endNum)
        {
            for (int i = startNum; i <= endNum; i++)
            {
                Chapter chap = new Chapter();

                chap._mangaId = manga.MangaId;
                chap.ChapterFileName = "Chapter_" + i.ToString("D3");
                chap.ChapterFileLink = String.Format("http://zoha.com.au/manga/{0}/{1}{2}.zip", manga.FolderName, prefix, i.ToString("D3"));
                chap.ChapterName = "Chapter " + i.ToString("D3");
                chap.CurrentIndex = 0;
                chap.IsDownloaded = 0;

                MangaForYouDB.Chapters.InsertOnSubmit(chap);
            }
            MangaForYouDB.SubmitChanges();
        }

        public Manga GetFirstMangaHasAutoDownload()
        {
            try
            {
                //  join c in Customers on o.CustomerID equals c.CustomerID
                // Query to specific chapter
                Manga manga =
                    (from Manga m in MangaForYouDB.Mangas

                     where m.IsAutoDownload == true
                     select m).First();

                return manga;
            }
            catch
            {
                return null;
            }
        }

        public void UpdateIsAutoDownloadByMangaId(int mangaId, bool value)
        {
            Manga manga =
                (from Manga m in MangaForYouDB.Mangas
                 where m.MangaId == mangaId
                 select m).First();
            manga.IsAutoDownload = value;
            MangaForYouDB.SubmitChanges();
        }

        internal void InsertChapter(Manga manga, VnSharing.ChapterInfo chapterInfo)
        {
            Chapter chap = new Chapter();

            chap._mangaId = manga.MangaId;
            // chap.ChapterFileName = chapterInfo.Name;
            chap.ChapterFileName = chapterInfo.Link.Substring(chapterInfo.Link.LastIndexOf("/") + 1);
            chap.ChapterFileLink = chapterInfo.Link;
            chap.ChapterName = chapterInfo.Name;
            chap.CurrentIndex = 0;
            chap.IsDownloaded = 0;

            MangaForYouDB.Chapters.InsertOnSubmit(chap);

            MangaForYouDB.SubmitChanges();
        }

        internal void UpdateMangaImageName(int MangaId, string fileLink)
        {
            try
            {
                // Query to specific chapter
                var mangaUpdate =
                    (from Manga manga in MangaForYouDB.Mangas
                     where manga.MangaId == MangaId
                     select manga).First();

                // Change IsDownloaded value by 1 (downloaded)
                mangaUpdate.ImageName = fileLink;

                // Ask the DataContext to save all the changes.
                MangaForYouDB.SubmitChanges();
            }
            catch
            {
                
            }
        }

        internal void LoadAllChapters(bool blIncrease)
        {
            try
            {
                if (blIncrease == true)
                {
                    // Specify the query to get all chapters
                    var getAllChapters =
                        (from Chapter allChapters
                             in MangaForYouDB.Chapters
                         orderby allChapters.ChapterId
                         select allChapters
                         );
                    // Query the database and get all chapters
                    AllChapters = new ObservableCollection<Chapter>(getAllChapters);
                }
                else
                {
                    var getAllChapters =
                        (from Chapter allChapters
                             in MangaForYouDB.Chapters
                         orderby allChapters.ChapterId descending
                         select allChapters
                         );
                    // Query the database and get all chapters
                    AllChapters = new ObservableCollection<Chapter>(getAllChapters);
                }
              
            }
            catch
            {

            }
        }

        internal void GetChapterListByMangaId(int intMangaId, bool blIncrease)
        {
            try
            {
               
                if (blIncrease == true)
                {
                    // Get list chapter by manga identity
                    var getChaptersByMangaId =
                        (from Chapter chapters
                             in MangaForYouDB.Chapters
                         where chapters._mangaId == intMangaId

                         orderby chapters.ChapterId

                         select chapters);
                    // Query the database and get all chapters
                    AllChapters = new ObservableCollection<Chapter>(getChaptersByMangaId);
                }
                else
                {
                    // Get list chapter by manga identity
                    var getChaptersByMangaId =
                        (from Chapter chapters
                             in MangaForYouDB.Chapters
                         where chapters._mangaId == intMangaId

                         orderby chapters.ChapterId descending  

                         select chapters);
                    // Query the database and get all chapters
                    AllChapters = new ObservableCollection<Chapter>(getChaptersByMangaId);
                }
              
            }
            catch
            {

            }
        }

        internal int GetNumberOfChapterByMangaId(int mangaId)
        {
            try
            {
                // Specify the query to get all chapters
                var getAllChapters =
                    (from Chapter allChapters
                         in MangaForYouDB.Chapters
                         where allChapters._mangaId == mangaId
                     select allChapters);

                
                return getAllChapters.Count();
            }
            catch
            {
                return -1;
            }
        }
    }
}